package com.JudgeOnline.sql;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import com.heavenlake.wordapi.Document;

public class DocGenerator extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();

		String jsonStr = request.getParameter("jsonStr");
		if (jsonStr == null || jsonStr.equals("")){
			out.println("jsonStr is empty!");
			return;
		}
			
		
		//json存入数据库
		String driverName = "com.mysql.jdbc.Driver";
		String dbURL = "jdbc:mysql://localhost:3306/judge_online";
		String userName = "root";
		String userPwd = "123456";
		Connection conn;
		try {
			Class.forName(driverName);
			conn = DriverManager.getConnection(dbURL,userName,userPwd);
			String sql = "insert into exam2013_2014 (paper) values(?)";  //需要更多参数
			PreparedStatement pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1,jsonStr);
			pstmt.executeUpdate();
			
			pstmt.close();
			conn.close();
			}
			catch(Exception e){
				e.printStackTrace();
			}

		String address = request.getSession().getServletContext()
				.getRealPath(""); //物理地址

		JSONObject format = (JSONObject) JSONValue.parse(jsonStr);
		JSONArray part = (JSONArray) format.get("part");
		String course_name = format.get("course_name").toString();

		String[] num = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十",
				"十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十" };

		Document doc = null;

		// 生成文档
		try {
			doc = new Document();
			doc.open(address + "\\doc\\template.doc");
			doc.insertAtBookmark("bookmark_subject", course_name);
			// doc.insertAtBookmark("bookmark_identify",
			// new java.io.File("E:\\Pictures\\头像.jpg"));
			
			//构造每道大题的结构
			for (int i = 1; i <= Integer.parseInt((String) format.get("count")); i++) {
				JSONObject part_i = (JSONObject) part.get(i - 1);
				int count = Integer.parseInt((String) part_i.get("count"));
				JSONArray question_score = (JSONArray) part_i
						.get("question_score");

				String docStr = num[i] + "、" + part_i.get("type") + "（" + part_i.get("score") + "分）";
				
				//检查所有小题分数是否全等
				boolean equal = true;
				for (int j = 1; j < count; j++)
					if (!(question_score.get(0)).equals(question_score.get(j))) {
						equal = false;
						break;
					}
				
				//全等，小题分数标在大题号之后
				if (equal) {
					docStr += "（每题" + question_score.get(0) + "分，共"
							+ count + "题）\n";
					for (int j = 1; j <= count; j++)
						docStr += j + ". \n";
					
				//不全等，小题分数分开
				} else {
					docStr += "\n";
					for (int j = 1; j <= count; j++)
						docStr += j + ". （" + question_score.get(j-1) + "分）\n";
				}
				
				//插入对应的大题书签处
				doc.insertAtBookmark("bookmark_problem" + i, docStr);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (doc != null)
					doc.saveAs(address + "\\doc\\" + course_name + ".doc");
				doc.close(false);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		// 提供下载
		try {
			File file = new File(address + "\\doc\\" + course_name + ".doc");
			String filename = file.getName();
			// String ext = filename.substring(filename.lastIndexOf(".") +
			// 1).toUpperCase();

			InputStream fis = new BufferedInputStream(new FileInputStream(file));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();

			response.reset();

			response.addHeader("Content-Disposition", "attachment;filename="
					+ URLEncoder.encode(filename,"utf-8"));
					//+ new String(filename.getBytes("utf-8"), "ISO-8859-1")); //IE文件名乱码
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(
					response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

}
